import XEUtils from 'xe-utils';
import TableUtils from '@/components/tables/cfg/table-utils'
import { VfUtils } from '@/utils/vf-utils';
import { watch, ref, reactive, nextTick } from 'vue';

export const useRowHandle = ({ props, tableRef, templateRow, tableOptions, tableDataHandle }) => {

  // ------ 表格事件操作
  const tableChecked = ref(false);
  const addTypeSelected = ref(false);
  const splitBtnDisabled = ref(true);
  const tableCheckedItems = ref([]);
  const tableCheckedTreeItems = ref([]);
  /** 复选框选中改变时触发 */
  const tableCheckboxChange = ({ records }) => {
    tableCheckedItems.value = records;
    const { flag, msg } = validateMergeRows();
    tableChecked.value = flag;
    const recordsTree = XEUtils.toArrayTree(records);
    if (recordsTree.length === 1) {
      if (recordsTree[0].children && recordsTree[0].children.length) {
        splitBtnDisabled.value = false;
      } else {
        splitBtnDisabled.value = true;
      }
    } else {
      splitBtnDisabled.value = true;
    }
    tableCheckedTreeItems.value = recordsTree;
  };
  /** 还原表格选中状态 */
  const clearTableSelected = () => {
    tableRef.value.clearCheckboxRow();
    tableChecked.value = false;
    addTypeSelected.value = false;
    splitBtnDisabled.value = true;
    tableCheckedItems.value = [];
    tableCheckedTreeItems.value = [];
  };
  /**
   * 滚动到指定行
   *
   * @param {Object} rowItem 指定行
   */
  const scrollToRow = rowItem => {
    nextTick(() => {
      setTimeout(() => {
        tableRef.value.scrollToRow(rowItem);
      }, 300);
    });
  };
  /**
   * 新增行
   */
  const handleAddRow = () => {
    const gridRef = tableRef.value;
    const tableData = XEUtils.clone(tableOptions.data, true);
    const newRowItem = XEUtils.clone(templateRow, true);
    newRowItem.id = VfUtils.getUUID();
    newRowItem.title = '新增行';
    newRowItem.width = 100;
    newRowItem.field = getNewRowField(tableData, 'newField');
    newRowItem.level = 1;
    newRowItem.parentId = 0;
    // 插入节点
    tableData.unshift(newRowItem);
    // 数据赋值
    tableOptions.data = tableData;
    // 设置为编辑状态
    gridRef.setEditRow(newRowItem);
    // 设置所有树节点展开
    gridRef.setTreeExpand(newRowItem, true);
    // 清除选中
    clearTableSelected()
    // 滚动到指定行
    scrollToRow(newRowItem);
    // 转义表格数据
    tableDataHandle.parseTableData(tableData, { level: 1 });
  }
  /**
   * 合并行操作
   */
  const handleMergeRow = () => {
    // 没有勾选不可选中
    if (!tableCheckedItems.value.length) {
      TableUtils.openMessage('请选择需要合并的行！');
      return;
    }
    // 校验合并数据
    const { flag, msg, info } = validateMergeRows();
    if (!flag) {
      TableUtils.openMessage(msg);
      return;
    }
    // 封装表格数据
    const { data, mergeRowItem } = packageMergeRow(info);
    const gridRef = tableRef.value;
    // 设置封装数据
    tableOptions.data = data;
    // 设置所有树节点展开
    gridRef.setTreeExpand(mergeRowItem, true);
    // 设置为编辑状态
    gridRef.setEditCell(mergeRowItem, 'title');
    // 清空选中
    clearTableSelected();
    // 滚动到指定行
    scrollToRow(mergeRowItem);
  };
  /**
   * 封装合并行信息
   *
   * @param {Object} info 参数信息
   * @returns {Object} 封装后的数据
   */
  const packageMergeRow = info => {
    const tableData = XEUtils.clone(tableOptions.data, true);
    let finalResult = tableData;
    const excludeIds = [];
    const mergeRowItem = XEUtils.clone(templateRow, true);
    mergeRowItem.id = VfUtils.getUUID();
    mergeRowItem.title = '合并表头';
    mergeRowItem.field = getNewRowField(tableData, 'margeHeader');
    mergeRowItem.sortable = false;
    delete mergeRowItem.kind;
    const { selectedTreeItems } = info;
    // 设置合并行级别
    mergeRowItem['level'] = selectedTreeItems[0].level;
    if (info.parentId == 0) {
      // 获取插入的索引位置
      const findRowIndex = XEUtils.findKey(tableData, item => item.id === selectedTreeItems[0].id);
      upRowItemsLevel(selectedTreeItems).forEach(rowItem => {
        const newItem = XEUtils.clone(rowItem, true);
        newItem['parentId'] = mergeRowItem.id;
        excludeIds.push(newItem.id);
        if (newItem.hasOwnProperty('fixed')) delete newItem.fixed;
        mergeRowItem.children.push(newItem);
      });
      // 设置合并行其他信息
      delete mergeRowItem.width;
      // 过滤选中数据
      finalResult = tableDataHandle.filterTableData(tableData, { excludeIds });
      // 添加合并数据
      finalResult.splice(findRowIndex, 0, mergeRowItem);
    } else {
      const mergeParentNode = XEUtils.findTree(tableData, row => row.id === info.parentId);
      const mergeParentRowItem = mergeParentNode.item;
      // 获取插入的索引位置
      const findRowIndex = XEUtils.findKey(
        mergeParentRowItem.children,
        item => item.id === selectedTreeItems[0].id,
      );
      upRowItemsLevel(selectedTreeItems).forEach(rowItem => {
        const newItem = XEUtils.clone(rowItem, true);
        newItem['parentId'] = mergeRowItem.id;
        excludeIds.push(newItem.id);
        if (newItem.hasOwnProperty('fixed')) delete newItem.fixed;
        mergeRowItem.children.push(newItem);
      });
      // 设置合并行其他信息
      delete mergeRowItem.width;
      // 过滤选中数据
      finalResult = tableDataHandle.filterTableData(tableData, { excludeIds });
      // 添加合并数据
      mergeParentRowItem.children.splice(findRowIndex, 0, mergeRowItem);
    }
    // 转义表格数据
    finalResult = tableDataHandle.parseTableData(finalResult, { level: 1 });
    return {
      mergeRowItem,
      data: finalResult,
    };
  };
  /**
   * 校验选中行是否可以合并
   * @returns {Boolean} 是否通过
   */
  const validateMergeRows = () => {
    // 选中的数据
    const selectedItems = tableCheckedItems.value;
    // 选中行数据中存在子级的行
    const childrenItems = selectedItems.filter(item => item.children && item.children.length);
    // 选中行数据转换成树结构
    const selectedTreeItems = XEUtils.toArrayTree(selectedItems);
    // 选中数据的级别统计数
    const levelCounts = XEUtils.countBy(selectedItems, 'level');
    // 选中数据的级别
    const levelKeys = Object.keys(levelCounts);
    // 选中数据的父级id统计数
    const parentIdCounts = XEUtils.countBy(selectedItems, 'parentId');
    // 选中数据的父级Id
    const parentKeys = Object.keys(parentIdCounts);
    // 存在子级行转换为单数组格式数据
    const childrenItemsArray = XEUtils.toTreeArray(childrenItems);
    let mergeInfo = { type: 0 };

    if (!selectedItems.length) {
      return {
        msg: '请选择需要合并的行！',
        flag: false,
      };
    }
    // 如果只选择了一个情况
    if (selectedItems.length === 1) {
      return {
        msg: '需要至少两条合并的行，请重新选择！',
        flag: false,
      };
    }
    // 合并层级不超过五级
    const maxLevel = Math.max(...levelKeys);
    if (maxLevel == 5) {
      return {
        msg: '层级超过最大合并层级（5级），请重新选择！',
        flag: false,
      };
    }
    // 如果选择的节点为同一树结构，不可合并
    if (selectedTreeItems.length === 1) {
      return {
        msg: '选择节点不可包含树结构下所有节点，请重新选择！',
        flag: false,
      };
    }
    // 只有同一种级别的情况
    if (levelKeys.length === 1) {
      // 同一级别，相同的父级节点
      if (parentKeys.length === 1) {
        mergeInfo = { type: 1, parentId: parentKeys[0] };
      } else {
        // 同一级别，存在不同的父级节点
        return {
          msg: '不支持跨级合并，请重新选择！',
          flag: false,
        };
      }
    } else {
      // 不同级别，不存在父节点
      // 选中节点中的父节点是否完全对等
      const sameFlag = XEUtils.includeArrays(
        selectedTreeItems.map(item => item.id),
        childrenItems.map(item => item.id),
      );
      // 选中数据中存在子级节点的父级id统计
      const childrenParentIdCounts = XEUtils.countBy(childrenItems, 'parentId');
      // 选中数据转换为树机构的父节点统计数
      const selectTreeParentIdCounts = XEUtils.countBy(selectedTreeItems, 'parentId');
      if (sameFlag && childrenItems.length === selectedTreeItems.length) {
        if (
          childrenItemsArray.length === selectedItems.length &&
          Object.keys(childrenParentIdCounts).length === 1
        ) {
          mergeInfo = { type: 2, parentId: Object.keys(selectTreeParentIdCounts)[0] };
        } else {
          return {
            msg: '不支持跨级合并，请重新选择！',
            flag: false,
          };
        }
      } else {
        if (Object.keys(selectTreeParentIdCounts).length === 1) {
          mergeInfo = { type: 3, parentId: Object.keys(selectTreeParentIdCounts)[0] };
        } else {
          return {
            msg: '不支持跨级合并，请重新选择！',
            flag: false,
          };
        }
      }
    }

    return {
      msg: '校验通过',
      flag: true,
      info: {
        ...mergeInfo,
        selectedItems,
        selectedTreeItems,
      },
    };
  };

  // ------ 删除行操作
  const handleDeleteRow = () => {
    const gridRef = tableRef.value;
    const selectedItems = tableCheckedItems.value;
    if (!selectedItems.length) return;
    const tableData = XEUtils.clone(tableOptions.data, true);
    const newTableDataArray = XEUtils.toTreeArray(tableData).filter(
      item => !selectedItems.map(item => item.id).includes(item.id),
    );
    const newTableData = XEUtils.toArrayTree(newTableDataArray);
    // 设置封装数据
    tableOptions.data = newTableData;
    // 清空选中
    clearTableSelected();
  };
  // ------ 拆分行操作
  const handleSplitRow = () => {
    // 没有勾选不可选中
    if (!tableCheckedItems.value.length) {
      TableUtils.openMessage('请选择需要拆分的行！');
      return;
    }
    if (splitBtnDisabled.value) {
      TableUtils.openMessage('所选行符合条件，请重新选择！');
      return;
    }
    let tableData = XEUtils.clone(tableOptions.data, true);
    const selectedTreeItems = tableCheckedTreeItems.value;
    const selectedItem = selectedTreeItems[0];
    const selectedChildren = selectedItem.children;
    // 获取选中
    const selectedItemNode = XEUtils.findTree(tableData, item => item.id === selectedItem.id);
    // 获取选中得父级
    const selectedParentNode = XEUtils.findTree(tableData, item => item.id === selectedItem.parentId);
    // 移除行
    if (selectedParentNode) {
      selectedParentNode.item.children = selectedParentNode.item.children.filter(
        item => item.id !== selectedItem.id,
      );
    } else {
      tableData = tableData.filter(item => item.id !== selectedItem.id);
    }
    let startIndex = selectedItemNode.index;
    selectedChildren.forEach((item, index) => {
      item.level = selectedItem.level;
      item.parentId = selectedItem.parentId;
      if (selectedParentNode) {
        selectedParentNode.item.children.splice(startIndex + index, 0, item);
      } else {
        tableData.splice(startIndex + index, 0, item);
      }
    });
    // 设置封装数据
    tableOptions.data = tableData;
    // 清空选中
    clearTableSelected();
  };

  /**
   * 获取新建行的字段信息
   *
   * @param {Array} tableData 表格数据
   * @param {String} prefix 前缀
   * @returns {String} 字段信息
   */
  const getNewRowField = (tableData, prefix = 'field') => {
    const margeHeaders = XEUtils.toTreeArray(tableData).filter(item => item.field.startsWith(prefix));
    return `${prefix}-${margeHeaders.length + 1}`;
  }

  /**
   * 改变行数据的level
   * @param {Array} selectedItems 目标数据
   * @returns {ObjArrayect} 处理后的数据
   */
  const upRowItemsLevel = selectedItems => {
    return selectedItems.map(rowItem => {
      rowItem['level'] = rowItem.level + 1;
      if (rowItem.children && rowItem.children.length) {
        rowItem.children = upRowItemsLevel(rowItem.children);
      }
      return rowItem;
    });
  };


  const handleClick = (code, params) => {
    switch (code) {
      case 'add':
        handleAddRow();
        break;
      case 'merge':
        handleMergeRow();
        break;
      case 'split':
        handleSplitRow();
        break;
      case 'delete':
        handleDeleteRow();
        break;
    }
  }

  return {
    handleClick,
    tableChecked,
    splitBtnDisabled,
    tableCheckedItems,
    tableCheckedTreeItems,
    tableCheckboxChange,
  }
}